package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService iCategoryService;

    @PostMapping
    public R addCategory(@RequestBody Category category,HttpSession session){

/*        Long shuju = (Long) session.getAttribute("shuju");
            category.setCreateUser(shuju);
            category.setCreateTime(LocalDateTime.now());
            category.setUpdateUser(shuju);
            category.setUpdateTime(LocalDateTime.now());*/
            iCategoryService.save(category);
            return R.success(category);
    }

    @GetMapping("/page")
    public R selectByPage(Integer page,Integer pageSize){

        IPage<Category> page1 = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        iCategoryService.page(page1, qw);

        List<Category> records = page1.getRecords();
        long total = page1.getTotal();

        Map data = new HashMap();
        data.put("records",records);
        data.put("total",total);

        return R.success(data);
    }

    @DeleteMapping
    public R deleteById(Long id){
        iCategoryService.remove(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R updateById(@RequestBody Category category,HttpSession session){

    /*    Long shuju = (Long) session.getAttribute("shuju");
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(shuju);*/

        iCategoryService.updateById(category);

        return R.success("成功");
    }

    @GetMapping("/list")
    public R list(Integer type){


        LambdaQueryWrapper<Category> lm = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> eq = lm.eq(type != null,Category::getType, type);

        eq.orderByDesc(Category::getSort);
        System.out.println(type);
        List<Category> data= iCategoryService.list(eq);

        System.out.println(data);
        return R.success(data);

    }


}
